package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                       .   ' \\| |// `.
//                        / \\||| : |||// \
//                       / _||||| -:- |||||- \
//                         | | \\\ - /// | |
//                        | \_| ''\---/'' | |
//                        \ .-\__ `-` ___/-. /
//                      ___`. .' /--.--\ `. . __
//                   ."" '< `.___\_<|>_/___.' >'"".
//                  | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                  \ \ `-. \_ __\ /__ _/ .-` / /
//          ======`-.____`-.___\_____/___.-`____.-'======
//                              `=---='
//
//          .............................................
//          佛祖镇楼                  BUG辟易
//          佛曰:
//          写字楼里写字间，写字间里程序员；
//          程序人员写程序，又拿程序换酒钱。
//          酒醒只在网上坐，酒醉还来网下眠；
//          酒醉酒醒日复日，网上网下年复年。
//          但愿老死电脑间，不愿鞠躬老板前；
//          奔驰宝马贵者趣，公交自行程序员。
//          别人笑我忒疯癫，我笑自己命太贱；
//          不见满街漂亮妹，哪个归得程序员？
@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;

    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        List<Comment> comments = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        List<Long> userId = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findbyIds(userId, null);
        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                String key = Constants.MOVEMENTS_INTERACT_KEY + comment.getId().toHexString();
                String lhashKey = Constants.PINGLUN_LIKE_HASHKEY + UserHolder.getUserId();
                if(redisTemplate.opsForHash().hasKey(key,lhashKey)) {
                    commentVo.setHasLiked(1);
                }
                list.add(commentVo);

            }
        }
        return new PageResult(page, pagesize, 0l, list);
    }

    public void saveComments(String movementId, String comment) {
        Long userId = UserHolder.getUserId();
        Comment comments = new Comment();
        comments.setUserId(userId);
        comments.setContent(comment);
        comments.setCreated(System.currentTimeMillis());
        comments.setPublishId(new ObjectId(movementId));
        comments.setCommentType(CommentType.COMMENT.getType());
        Integer contns = commentApi.save(comments);

    }

    public Integer likeComment(String movementId) {
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        String key = Constants.MOVEMENTS_INTERACT_KEY + UserHolder.getUserId();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    public Integer dislikeComment(String movementId) {
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        if (!hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);

        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    public Integer loveComment(String movementId) {
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        if (hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    public Integer disloveComment(String movementId) {
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        if (!hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);

        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    public Integer likeCommentCount(String comentsid) {
        //1.根据评论id查询出当前要点赞的评论
        Long userId = UserHolder.getUserId();
        ObjectId objectId = new ObjectId(comentsid);
        List<Comment> comments = commentApi.hasCount(objectId ,userId);
        Comment commentd = new Comment();
        for (Comment comment : comments) {
            commentd.setLikeCount(comment.getLikeCount());
        }
        System.out.println(commentd.getLikeCount());
     if (commentd.getLikeCount()!=0){
         commentApi.updatalikeCountj(comentsid);
         String key = Constants.MOVEMENTS_INTERACT_KEY + comentsid;
         String hashKey = Constants.PINGLUN_LIKE_HASHKEY + UserHolder.getUserId();
         redisTemplate.opsForHash().delete(key, hashKey);
         return null;
     }
           commentApi.updatalikeCount(comentsid);
        String key = Constants.MOVEMENTS_INTERACT_KEY + comentsid;
        String hashKey = Constants.PINGLUN_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
       return null;
    }
}
